<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form :inline="true">
      <el-form-item label="角色名称">
        <el-input v-model="q" placeholder="请输入角色名称" clearable @keyup.enter.native="fetchData" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchData">查询</el-button>
        <el-button type="primary" @click="addRole">新增角色</el-button>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      :data="roleList"
      border
      :header-cell-style="{ background: '#fafafa' }"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="role_key" label="角色编号" />
      <el-table-column prop="create_time" label="创建时间" />
      <el-table-column label="操作" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="editRole(scope.row)">编辑</el-button>
          <el-button type="text" @click="authRole(scope.row)">授权</el-button>
          <el-button type="text" @click="singleDeleteRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="fetchData" />

    <el-drawer :title="roleDrawerTitle" :visible.sync="roleDrawerShow" direction="rtl" :before-close="handleCloseDrawer">
      <div class="drawer-container-scroll">
        <el-form v-if="basicInfo" ref="roleForm" :model="roleForm" :rules="roleFormRules" label-width="90px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色编号" prop="role_key">
            <el-input v-model="roleForm.role_key" placeholder="请输入角色编号" />
          </el-form-item>
          <el-form-item label="排序" prop="order">
            <el-input-number v-model="roleForm.order" :min="1" :max="999" label="排序序号" />
          </el-form-item>
          <el-form-item label="最高权限">
            <el-radio-group v-model="roleForm.is_admin">
              <el-radio :label="true">使用</el-radio>
              <el-radio :label="false">不使用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="roleForm.disabled">
              <el-radio :label="false">正常</el-radio>
              <el-radio :label="true">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="roleForm.desc" type="textarea" :rows="2" placeholder="请输入描述" />
          </el-form-item>
        </el-form>
        <el-form v-if="!basicInfo" ref="roleForm" :model="roleForm" :rules="roleFormRules" label-width="90px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" placeholder="请输入角色名称" disabled />
          </el-form-item>
          <el-form-item label="数据权限">
            <el-select v-model="roleForm.data_range" placeholder="请选择数据权限">
              <el-option
                v-for="item in dataRangeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.value === 3"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="菜单权限">
            <el-tree
              ref="treeRef"
              :data="menuOptions"
              :props="props"
              :node-key="props.id"
              default-expand-all
              show-checkbox
              @check-change="handleMenuCheckChange"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="drawer-footer__btn">
          <el-button @click="handleCloseDrawer">取 消</el-button>
          <el-button type="primary" @click="saveSubmit">保 存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import apiRole from '@/api/system/role'
import apiMenu from '@/api/system/menu'
import Pagination from '@/components/Pagination'
const defaultForm = {
  id: '',
  name: '',
  role_key: '',
  is_admin: false,
  disabled: false,
  order: 1,
  desc: '',
  data_range: 4,
  menu_ids: []
}

export default {
  components: { Pagination },
  data() {
    return {
      roleList: [],
      menuOptions: [],
      roleInfo: {},
      listLoading: false,
      basicInfo: true,
      page: 1,
      limit: 10,
      total: 0,
      q: '',
      roleDrawerShow: false,
      roleDrawerTitle: '新增用户',
      submitType: 0, // 0:新增 1:编辑
      roleForm: defaultForm,
      roleFormRules: {
        role_key: [
          { required: true, message: '角色编号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        order: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ]
      },
      dataRangeOptions: [
        { value: 0, label: '仅本人得数据' },
        { value: 1, label: '本部门数据' },
        { value: 2, label: '本部门及以下数据' },
        { value: 3, label: '自定义数据权限' },
        { value: 4, label: '全部数据' }
      ],
      props: {
        id: 'value',
        name: 'label',
        children: 'children'
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const params = {
        page: this.page,
        limit: this.limit,
        name: this.q
      }
      apiRole.getRoleList(params).then(response => {
        this.roleList = response.data
        this.total = response.count
      })
      this.listLoading = false
    },
    getMenuOptions() {
      apiMenu.getMenuOptions().then(response => {
        this.menuOptions = response.data
      })
    },
    handleCloseDrawer() {
      this.roleDrawerShow = false
    },
    addRole() {
      this.getMenuOptions()
      this.roleDrawerShow = true
      this.basicInfo = true
      this.roleDrawerTitle = '新增角色'
      this.submitType = 0
      this.roleForm = Object.assign({}, defaultForm)
    },
    editRole(row) {
      this.roleDrawerShow = true
      this.basicInfo = true
      this.roleDrawerTitle = '编辑角色'
      this.submitType = 1
      this.roleForm = Object.assign({}, row)
    },
    async authRole(row) {
      this.getMenuOptions()
      this.roleDrawerShow = true
      this.basicInfo = false
      this.roleDrawerTitle = '角色授权'
      this.submitType = 1
      this.roleForm = Object.assign({}, row)
      await this.checkedMenusByRoleInfo(row)
    },
    async checkedMenusByRoleInfo(row) {
      apiRole.getRoleInfo(row).then(response => {
        const checkedIds = response.data.menus.map(item => item.id)
        checkedIds.forEach(checkedId => {
          this.$refs.treeRef.setChecked(checkedId, true, false)
        })
      })
    },
    handleMenuCheckChange() {
      const checkedKeys = this.$refs.treeRef.getCheckedKeys()
      const halfCheckedKeys = this.$refs.treeRef.getHalfCheckedKeys()
      this.roleForm.menu_ids = [...checkedKeys, ...halfCheckedKeys]
    },
    async saveSubmit() {
      await this.$refs.roleForm.validate(async validate => {
        if (validate) {
          if (this.submitType === 0) {
            await apiRole.createRole(this.roleForm).then(response => {
              this.$message.success(response.message || '新增成功')
            }).catch(error => {
              this.$message.error(error.response.data['message'])
            })
          } else {
            await apiRole.updateRole(this.roleForm).then(response => {
              this.$message.success(response.message || '编辑成功')
            }).catch(error => {
              this.$message.error(error.response.data['message'])
            })
          }
          this.roleDrawerShow = false
          await this.fetchData()
        }
      })
    },
    async singleDeleteRole(row) {
      const data = [row.id]
      await this.deleteSubmit(data)
    },
    async deleteSubmit(data) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        lockScroll: false,
        type: 'warning'
      }).then(async() => {
        await apiRole.deleteRole(data).then(async response => {
          this.$message.success(response.message || '删除成功')
          await this.fetchData()
        })
      })
    }
  }
}
</script>
